<template>
  <a-modal
    title="物流信息"
    :width="640"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="loading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="loading">
      <a-form-model
        :model="model"
        v-bind="formLayout"
        ref="ruleForm"
        :rules="rules"
        @submit.native.prevent>
        <a-form-model-item
          label="物流公司"
          prop="expressCompany">
          <a-input size="large" v-model="model.expressCompany" />
        </a-form-model-item>
        <a-form-model-item
          label="物流单号"
          prop="expressNo">
          <a-input size="large" v-model="model.expressNo" />
        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
// import pick from 'lodash.pick'

// 表单字段
const fields = ['orderNo', 'expressCompany', 'expressNo']

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    model: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      loading: false,
      rules: {
        expressCompany: [{ required: true, message: '物流公司必填', trigger: ['blur', 'change'] }],
        expressNo: [{ required: true, message: '物流单号必填', trigger: ['blur', 'change'] }]
      },
      form: this.$form.createForm(this)
    }
  },
  created () {
    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    // this.$watch('model', () => {
    //   this.model && this.form.setFieldsValue(pick(this.model, fields))
    // })
  },
  methods: {
    // 弹出框-确定
    handleOk (e) {
      const {
        edit
      } = this
      this.loading = true
      // 验证表单
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          edit()
        } else {
          const _this = this
          setTimeout(() => {
            _this.loading = false
          }, 600)
        }
      })
    },
    // 弹出框-取消
    handleCancel (e) {
      // 重置表单数据
      this.$refs.ruleForm.resetFields()
      this.$emit('cancel')
    },
    // 编辑处理
    edit () {
      this.$common.handlePost('/orders/express', this.model)
        .then(res => {
          if (res.code === 200) {
            this.$message.success(res.msg)
            // 重置表单数据
            this.$refs.ruleForm.resetFields()
            // 关闭弹框
            this.$emit('ok')
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          this.$message.error(err)
        })
        .finally(() => {
          this.loading = false
        })
    }
  }
}
</script>
